//
//  YFSportAnalysisVc.m
//  SquashSpark
//
//  Created by Coollang on 2017/12/7.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "YFSportAnalysisVc.h"
#import "JCLabel.h"
#import "YFSportAndSensorApi.h"
#import <DateTools/DateTools.h>
#import "NSAttributedString+RichText.h"
#import "UIImage+YFExtension.h"

@import Charts;

@interface YFSportAnalysisVc ()

@property (weak, nonatomic) IBOutlet UIImageView *racketImageView;
@property (weak, nonatomic) IBOutlet UILabel *dateLabel;
@property (weak, nonatomic) IBOutlet JCLabel *sweetPecentLabel;
@property (weak, nonatomic) IBOutlet JCLabel *foreHandPecentLabel;

@property (weak, nonatomic) IBOutlet UILabel *exerciseTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *swingsLabel;
@property (weak, nonatomic) IBOutlet UILabel *caloriesLabel;

@property (weak, nonatomic) IBOutlet UILabel *swingSpeedAvgLabel;
@property (weak, nonatomic) IBOutlet UILabel *swingSpeedMaxLabel;
@property (weak, nonatomic) IBOutlet UILabel *swingSpeedMinLabel;
@property (weak, nonatomic) IBOutlet LineChartView *swingSpeedLine;
@property (weak, nonatomic) IBOutlet UILabel *swingSpeedUnitLabel;

@property (weak, nonatomic) IBOutlet UILabel *powerAvgLabel;
@property (weak, nonatomic) IBOutlet UILabel *powerMaxLabel;
@property (weak, nonatomic) IBOutlet UILabel *powerMinLabel;
@property (weak, nonatomic) IBOutlet LineChartView *powerLine;

@property (weak, nonatomic) IBOutlet UILabel *swingTimeAvgLabel;
@property (weak, nonatomic) IBOutlet UILabel *swingTimeMaxLabel;
@property (weak, nonatomic) IBOutlet UILabel *swingTimeMinLabel;
@property (weak, nonatomic) IBOutlet LineChartView *swingTimeLine;

@end

@implementation YFSportAnalysisVc

- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.yearMonthDayStr == nil) {
        self.yearMonthDayStr = [[NSDate date] formattedDateWithFormat:@"yyyy-MM-dd"];
    }
    [self initCode];
    [self loadData];
    
}

- (void)updateUIWithDayItem:(YFDayRecordItem *)dayItem {
    
    CGFloat sweetReat = (dayItem.sweetHitTimes * 1.0)/ dayItem.dayAmountOfCount;
    sweetReat = dayItem.dayAmountOfCount > 0 ? sweetReat:0;
    self.racketImageView.image = [UIImage imageNamed:[self racketGradeImageWithSweatReat:sweetReat]];
    [self.sweetPecentLabel setValue:[NSString stringWithFormat:@"%0.f",(sweetReat * 100)] valueFont:24 valueColor:[UIColor whiteColor] unit:@"%" unitFont:12 unitColor:[UIColor whiteColor]];
    CGFloat forehandReat = (dayItem.foreHandCount * 1.0)/ dayItem.dayAmountOfCount;
    forehandReat = dayItem.dayAmountOfCount > 0 ? forehandReat:0;
    [self.foreHandPecentLabel setValue:[NSString stringWithFormat:@"%0.f",(forehandReat * 100)] valueFont:24 valueColor:[UIColor whiteColor] unit:@"%" unitFont:12 unitColor:[UIColor whiteColor]];
    
    [self setSportTime:dayItem.sportTimeInterval calorie:dayItem.dayCalories swingCount:dayItem.dayAmountOfCount];
    
    // 重新绘制曲线
    NSMutableArray *speedArrM = [NSMutableArray arrayWithCapacity:dayItem.detailItems.count];
    NSMutableArray *powerArrM = [NSMutableArray arrayWithCapacity:dayItem.detailItems.count];
    NSMutableArray *timeArrM = [NSMutableArray arrayWithCapacity:dayItem.detailItems.count];
    
    for (YFSwingDetailItem *detailItem in dayItem.detailItems) {
        if ([YFUserDefaults generalMetricSystemUnit]) {
            [speedArrM addObject:@(detailItem.swingSpeed)];
        }else {
            [speedArrM addObject:@([Common kmhToMph:detailItem.swingSpeed])];
        }
        [powerArrM addObject:@(detailItem.strength)];
        [timeArrM addObject:@(detailItem.swingTime)];
    }
    
    [self setLineChartViewData:speedArrM.mutableCopy forView:_swingSpeedLine color:UIColorFromHex(0x2bcae8)];
    [self setLineChartViewData:powerArrM.mutableCopy forView:_powerLine color:UIColorFromHex(0xea4947)];
    [self setLineChartViewData:timeArrM.mutableCopy forView:_swingTimeLine color:UIColorFromHex(0x29d9c2)];
}

// 根据比例来显示甜区图片
- (NSString *)racketGradeImageWithSweatReat:(CGFloat)sweatReat {
    if (sweatReat <= 0) {
        return @"home_racket0";
    }else if (sweatReat < 30){
        return @"home_racket1";
    }else if (sweatReat < 50){
        return @"home_racket2";
    }else if (sweatReat < 70){
        return @"home_racket3";
    }else if (sweatReat < 90){
        return @"home_racket4";
    }else {
        return @"home_racket5";
    }
}

// 加载数据
- (void)loadData {
    RLMResults *result = [[YFDayRecordItem getUserAllDayRecordItems] objectsWhere:@"dayDate == %@",self.yearMonthDayStr];
    if (result.count == 0) {
        // 提示没数据
        return;
    }
    YFDayRecordItem *dayItem = result.firstObject;
    __weak typeof(self) weakSelf = self;
    if (dayItem.dayAmountOfCount == dayItem.detailItems.count) {
        // 没必要去网上下
        [self updateUIWithDayItem:dayItem];
    }else {
        YFSportAndSensorApi *getDayDetailApi = [YFSportAndSensorApi getDayStatisticsDetailWithDay:self.yearMonthDayStr];
        [[YFNetworkingService sharedInstance] sendRequest:getDayDetailApi callback:^(BOOL success, id result, NSError *error) {
            if (success) {
                NSArray *responseinfo = [getDayDetailApi responseInfo];
                for (NSDictionary *dict in responseinfo) {
                    YFSwingDetailItem *detailItem = [[YFSwingDetailItem alloc] init];
                    [detailItem swingDetailItemFormServerDict:dict];
                    [dayItem addDetailItem:detailItem isUpdate:YES];
                }
                [self updateUIWithDayItem:dayItem];
            }else {
                // 提示数据加载失败
                [MBProgressHUD showFailHudInView:weakSelf.view message:@"Load data fail!" afterDelay:1.5];
            }
        }];
    }
}


- (void)initCode {
    self.navigationItem.title = @"Swing Analysis";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"share_icon"] style:UIBarButtonItemStyleDone target:self action:@selector(shareAction:)];
    [self.sweetPecentLabel setValue:@"0" valueFont:24 valueColor:[UIColor whiteColor] unit:@"%" unitFont:12 unitColor:[UIColor whiteColor]];
    [self.foreHandPecentLabel setValue:@"0" valueFont:24 valueColor:[UIColor whiteColor] unit:@"%" unitFont:12 unitColor:[UIColor whiteColor]];
    self.tableView.showsVerticalScrollIndicator = NO;
    
    self.dateLabel.text = [self.yearMonthDayStr stringByReplacingOccurrencesOfString:@"-" withString:@"/"];
    
    [self setupLineChartView:_swingSpeedLine];
    [self setupLineChartView:_powerLine];
    [self setupLineChartView:_swingTimeLine];
    
    NSMutableArray *am = [NSMutableArray array];
    for (NSInteger i = 0; i < arc4random()%100; i++) {
        [am addObject:@(arc4random()%1000).stringValue];
    }
//    [self setLineChartViewData:am.mutableCopy forView:_swingSpeedLine color:UIColorFromHex(0x2bcae8)];
    
    NSMutableArray *an = [NSMutableArray array];
    for (NSInteger i = 0; i < arc4random()%100; i++) {
        [an addObject:@(arc4random()%1000).stringValue];
    }
//    [self setLineChartViewData:an.mutableCopy forView:_powerLine color:UIColorFromHex(0xea4947)];
    
    NSMutableArray *at = [NSMutableArray array];
    for (NSInteger i = 0; i < arc4random()%100; i++) {
        [at addObject:@(arc4random()%1000).stringValue];
    }
//    [self setLineChartViewData:at.mutableCopy forView:_swingTimeLine color:UIColorFromHex(0x29d9c2)];
}

- (void)shareAction:(UIBarButtonItem *)sender{
    // 获取截图
    UIImage *cutImage = [UIImage imageFromView:self.tableView];
    NSArray *images = @[cutImage];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        UIActivityViewController *activityController = [[UIActivityViewController alloc] initWithActivityItems:images applicationActivities:nil];
        [self.navigationController presentViewController:activityController animated:YES completion:nil];
    });
}

#pragma mark - 设置LineChartView
/*!
 *  初始化曲线视图
 */
- (void)setupLineChartView:(LineChartView *)chartView{
    
    chartView.descriptionText = @"";
    chartView.noDataText = @"";
    chartView.legend.enabled = NO;
    
    chartView.scaleYEnabled = NO;
    chartView.scaleXEnabled = NO;
    chartView.scaleEnabled = NO;
    chartView.doubleTapToZoomEnabled = NO;
    chartView.dragDecelerationEnabled = NO;
    chartView.dragDecelerationFrictionCoef = 0;
    chartView.leftAxis.enabled = NO;
    
    chartView.xAxis.enabled = NO;
//    chartView.xAxis.labelPosition = XAxisLabelPositionBottom;
//    chartView.xAxis.drawGridLinesEnabled = NO;
//    chartView.xAxis.labelTextColor = UIColorFromHex(0x999999);
//    chartView.xAxis.axisLineColor = UIColorFromHex(0x999999);
//    chartView.xAxis.labelFont = kOpenSansFont(OpenSansBold, 10);
//    chartView.xAxis.drawAxisLineEnabled = NO;
    
    chartView.rightAxis.drawZeroLineEnabled = NO;
    chartView.rightAxis.enabled = YES;
    chartView.rightAxis.drawGridLinesEnabled = YES;
    chartView.rightAxis.drawLabelsEnabled = YES;
    chartView.rightAxis.drawAxisLineEnabled = NO;
    chartView.rightAxis.labelTextColor = UIColorFromHex(0x999999);
    chartView.rightAxis.axisLineColor = UIColorFromHex(0x999999);
    chartView.rightAxis.labelFont = kOpenSansFont(OpenSansRegular, 10);
//    chartView.rightAxis.zeroLineWidth = 0.5;
//    chartView.rightAxis.zeroLineColor = UIColorFromHex(0x999999);
//    chartView.rightAxis.axisMaximum = 1000;
}

/*!
 *  加载曲线数据
 */

- (void)setLineChartViewData:(NSArray <NSString *> *)values
                     forView:(LineChartView *)lineChartView
                       color:(UIColor *)color {
    
    NSMutableArray *arr = [NSMutableArray array];
    CGFloat maxValue = 0;
    CGFloat minValue = CGFLOAT_MAX;
    CGFloat totalVale = 0;
    
    if (values.count <= 0) {
        minValue = 0;
    }
    for (NSInteger i = 0; i < values.count; i++) {
        CGFloat value = [values[i] floatValue];
        maxValue = maxValue > value ? maxValue : value;
        minValue = minValue < value ? minValue : value;
        totalVale += value;
        ChartDataEntry *entry = [[ChartDataEntry alloc] initWithX:i y:value];
        [arr addObject:entry];
    }
    LineChartDataSet *set = [[LineChartDataSet alloc] initWithValues:arr label:nil];
    //对于线的各种设置
    set.lineWidth = 2;//线宽
    set.drawValuesEnabled = NO;//不显示文字
    set.drawCirclesEnabled = NO;//是否绘制拐点
    set.circleRadius = 5.0f;//拐点半径
    set.circleColors = @[color];
    set.drawCircleHoleEnabled = YES;//是否绘制中间的空心
    set.circleHoleRadius = 3.0f;//空心的半径
    set.circleHoleColor = [UIColor whiteColor];//空心的颜色
    set.mode = LineChartModeLinear;// 折线模式
    set.drawFilledEnabled = NO;//是否填充颜色
    [set setColor:color];//折线颜色
    
    lineChartView.data = nil;
    lineChartView.data = [[LineChartData alloc] initWithDataSet:set];
    [lineChartView animateWithYAxisDuration:1.0f easingOption:ChartEasingOptionEaseInOutQuad];
    
    totalVale = totalVale >= 0 ? totalVale : 0;
    maxValue = maxValue >= 0 ? maxValue : 0;
    minValue = minValue >= 0 ? minValue : 0;
    
    if (lineChartView == _swingSpeedLine) {
        if ([YFUserDefaults generalMetricSystemUnit]) {
            self.swingSpeedUnitLabel.text = @"Swing Speed(kph)";
            _swingSpeedMaxLabel.text = [NSString stringWithFormat:@"%ld(max)",(NSInteger)maxValue];
            _swingSpeedMinLabel.text = [NSString stringWithFormat:@"%ld(min)",(NSInteger)minValue];
            _swingSpeedAvgLabel.text = values.count <= 0 ? @"0":@((NSInteger)(totalVale/values.count)).stringValue;
        }else {
            self.swingSpeedUnitLabel.text = @"Swing Speed(mph)";
            self.swingSpeedAvgLabel.text = values.count <= 0 ? @"0":[NSString stringWithFormat:@"%0.f",round([Common kmhToMph:(totalVale/values.count)])];
            self.swingSpeedMaxLabel.text = [NSString stringWithFormat:@"%0.f(max)",round([Common kmhToMph:maxValue])];
            self.swingSpeedMinLabel.text = [NSString stringWithFormat:@"%0.f(min)",round([Common kmhToMph:minValue])];
        }
    }else if (lineChartView == _powerLine) {
        _powerMaxLabel.text = [NSString stringWithFormat:@"%ld(max)",(NSInteger)maxValue];
        _powerMinLabel.text = [NSString stringWithFormat:@"%ld(min)",(NSInteger)minValue];
        _powerAvgLabel.text = values.count <= 0 ? @"0":@((NSInteger)(totalVale/values.count)).stringValue;
    }else if (lineChartView == _swingTimeLine) {
        _swingTimeMaxLabel.text = [NSString stringWithFormat:@"%ld(max)",(NSInteger)maxValue];
        _swingTimeMinLabel.text = [NSString stringWithFormat:@"%ld(min)",(NSInteger)minValue];
        _swingTimeAvgLabel.text = values.count <= 0 ? @"0":@((NSInteger)(totalVale/values.count)).stringValue;
    }
}

- (void)setSportTime:(NSInteger)sportTime calorie:(NSInteger)calorie swingCount:(NSInteger)swingCount {
    UIFont *bigFont = kOpenSansFont(OpenSansRegular, 20);
    UIFont *smallFont = kOpenSansFont(OpenSansRegular, 12);
    
    self.exerciseTimeLabel.attributedText = [NSAttributedString attriWithSeconds:sportTime hAndMFont:smallFont numberFont:bigFont textColor:kTWhiteText];
    if (calorie > 0) {
        NSString *calorieStr = [NSString stringWithFormat:@"%zdcal",calorie];
        self.caloriesLabel.attributedText = [NSAttributedString attributedString:calorieStr subString:@[@(calorie).stringValue,@"cal"] colors:@[kTWhiteText] fonts:@[bigFont,smallFont]];
    }else {
        self.caloriesLabel.text = @"0";
    }
    self.swingsLabel.text = @(swingCount).stringValue;
}

@end
